package com.example.restatr.Atcivity.LawyerConsultation;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.LawyerConsultation.Bean.LawyerEvaluateBean;
import com.example.restatr.Atcivity.LawyerConsultation.Bean.LawyerInfoBean;
import com.example.restatr.Atcivity.LawyerConsultation.Bean.LegalAdviceBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LawyerInfoAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private ImageView head;
    private TextView name;
    private TextView workStartAt;
    private TextView serviceTimes;
    private TextView favorableRate;
    private TextView legalExpertiseName;
    private TabLayout tabLayout;
    private LinearLayout infoLL;
    private TextView baseInfo;
    private TextView eduInfo;
    private TextView licenseNo;
    private ImageView certificateImgUrl;
    private RecyclerView rv;
    private LawyerInfoBean.RowsBean data;
    private List<LawyerEvaluateBean.RowsBean> rowsBeans = new ArrayList<>();
    private RvAdapter rvAdapter = new RvAdapter();
    private LinearLayout Null;
    private TextView nullText;
    private LinearLayout loading;
    private TabLayout.Tab tabAt;
    private CardView btn;
    private RelativeLayout pl;
    private EditText plEdText;
    private MaterialButton button;
    private float ratingScore;
    private LegalAdviceBean.RowsBean rowsBean;//我的咨询bean

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lawyer_info_at);
        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        head = findViewById(R.id.head);
        name = findViewById(R.id.name);
        workStartAt = findViewById(R.id.workStartAt);
        serviceTimes = findViewById(R.id.serviceTimes);
        favorableRate = findViewById(R.id.favorableRate);
        legalExpertiseName = findViewById(R.id.legalExpertiseName);
        tabLayout = findViewById(R.id.tabLayout);
        infoLL = findViewById(R.id.info_LL);
        baseInfo = findViewById(R.id.baseInfo);
        eduInfo = findViewById(R.id.eduInfo);
        licenseNo = findViewById(R.id.licenseNo);
        certificateImgUrl = findViewById(R.id.certificateImgUrl);
        btn = findViewById(R.id.btn);
        rv = findViewById(R.id.rv);
        Null = findViewById(R.id.Null);
        nullText = findViewById(R.id.null_text);
        loading = findViewById(R.id.loading);
        pl = findViewById(R.id.pl);
        plEdText = findViewById(R.id.pl_edText);
        button = findViewById(R.id.button);

        nullText.setText("暂无评论...");
        loading.setVisibility(View.GONE);
        data = new Gson().fromJson(getIntent().getStringExtra("data"), new TypeToken<LawyerInfoBean.RowsBean>() {
        }.getType());
        Tools.SetBarTitle(toolbar, barTitle, "律师详情", search, this, false);
        Glide.with(this)
                .load(Tools.ip + data.getAvatarUrl())
                .transform(new CircleCrop())
                .into(head);
        name.setText(data.getName());
        workStartAt.setText("从业时间" + data.getWorkStartAt());
        serviceTimes.setText(data.getServiceTimes() + "人咨询");
        favorableRate.setText("好评率" + data.getFavorableRate() + "%");
        legalExpertiseName.setText(data.getLegalExpertiseName());
        SetInfo();
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getText().toString()) {
                    case "律师信息":
                        SetInfo();
                        loading.setVisibility(View.GONE);
                        Null.setVisibility(View.GONE);
                        break;
                    case "用户评价":
                        GetEvaluate();
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabAt = tabLayout.getTabAt(1);
        if (getIntent().getStringExtra("intent") != null) {
            tabAt.select();
            btn.setVisibility(View.GONE);
            pl.setVisibility(View.VISIBLE);
            rowsBean = new Gson().fromJson(getIntent().getStringExtra("rows"), new TypeToken<LegalAdviceBean.RowsBean>() {
            }.getType());
        }
        plEdText.setHint("本次咨询体验如何，快来写下您的评价吧！");
        plEdText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (plEdText.getText().toString().length() > 0) {
                    button.setVisibility(View.VISIBLE);
                } else {
                    button.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //评论按钮点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View inflate = getLayoutInflater().inflate(R.layout.wm_pj_dailog_layout, null);
                TextView text = inflate.findViewById(R.id.text);
                RatingBar rating = inflate.findViewById(R.id.rating);
                MaterialButton button = inflate.findViewById(R.id.button);
                AlertDialog.Builder builder = new AlertDialog.Builder(LawyerInfoAt.this);
                builder.setView(inflate).create();
                final AlertDialog show = builder.show();
                text.setText("电影评分");
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ratingScore = rating.getRating();
                        show.dismiss();
                        posComment();
                    }
                });
            }
        });
    }

    private void posComment() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", rowsBean.getId());
                jsonObject.put("evaluate", plEdText.getText().toString());
                jsonObject.put("score", ratingScore);
                String post = Tools.Post("/prod-api/api/lawyer-consultation/legal-advice/evaluate", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        pl.setVisibility(View.GONE);
                        GetEvaluate();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //评论点赞/取消赞
    private void PostEvaluateLike(int adviceId, boolean likeState, int pos) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("adviceId", adviceId);
                jsonObject.put("like", likeState);
                String post = Tools.Post("/prod-api/api/lawyer-consultation/legal-advice/evaluate-like", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        rowsBeans.get(pos).setMyLikeState(likeState);
                        if (likeState){
                            rowsBeans.get(pos).setLikeCount(rowsBeans.get(pos).getLikeCount() + 1);
                        }else {
                            rowsBeans.get(pos).setLikeCount(rowsBeans.get(pos).getLikeCount() - 1);
                        }
                        rvAdapter.notifyItemChanged(pos);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }).start();
    }

    //获取评论
    private void GetEvaluate() {
        rv.setVisibility(View.VISIBLE);
        infoLL.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
        rowsBeans.clear();
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/lawyer-consultation/lawyer/list-evaluate?lawyerId=" + data.getId(), MainActivity.sp.getString("token", ""));
            LawyerEvaluateBean lawyerEvaluateBean = new Gson().fromJson(token, LawyerEvaluateBean.class);
            rowsBeans.addAll(lawyerEvaluateBean.getRows());
            runOnUiThread(() -> {
                if (rowsBeans.size() > 0) {
                    rv.setAdapter(rvAdapter);
                    loading.setVisibility(View.GONE);
                } else {
                    loading.setVisibility(View.GONE);
                    Null.setVisibility(View.VISIBLE);
                }
            });
        }).start();
    }

    //展示信息
    private void SetInfo() {
        infoLL.setVisibility(View.VISIBLE);
        rv.setVisibility(View.GONE);
        baseInfo.setText(data.getBaseInfo());
        eduInfo.setText(data.getEduInfo());
        licenseNo.setText("执业证编号 " + data.getLicenseNo());
        Glide.with(LawyerInfoAt.this)
                .load(Tools.ip + data.getCertificateImgUrl().replaceFirst("/dev-api/", "/prod-api/"))
                .into(certificateImgUrl);
    }

    public void onClick(View view) {
        Intent intent = new Intent(this, LegalAdviceAt.class);
        intent.putExtra("data", new Gson().toJson(data));
        startActivity(intent);
    }

    class RvAdapter extends RecyclerView.Adapter<RvAdapter.RvViewHolder> {

        @NonNull
        @Override
        public RvViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate(R.layout.pj_list_item, parent, false);
            return new RvViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull RvViewHolder holder, int position) {
            Glide.with(LawyerInfoAt.this)
                    .load(Tools.ip + "/prod-api/" + rowsBeans.get(position).getFromUserAvatar())
                    .transform(new CircleCrop())
                    .error(R.drawable.ic_round_person_24)
                    .into(holder.head);
            holder.name.setText("用户" + rowsBeans.get(position).getFromUserName());
            holder.date.setText(rowsBeans.get(position).getCreateTime().substring(0, 10));
            holder.score.setRating(rowsBeans.get(position).getScore());
            if (rowsBeans.get(position).getScore() == 0) {
                holder.level.setText("此用户未打评分，不计入总评分");
            } else {
                Tools.GetLevel(rowsBeans.get(position).getScore(), holder.level);
            }
            if (rowsBeans.get(position).getEvaluateContent() != null) {
                holder.content.setText(rowsBeans.get(position).getEvaluateContent());
            } else {
                holder.content.setText("此用户未做评价！");
            }
            holder.likeLL.setVisibility(View.VISIBLE);
            holder.likeNum.setText(String.valueOf(rowsBeans.get(position).getLikeCount()));
            if (rowsBeans.get(position).isMyLikeState()) {
                holder.likeImg.setImageResource(R.drawable.ic_baseline_favorite_24);
            } else {
                holder.likeImg.setImageResource(R.drawable.ic_baseline_favorite_border_24);
            }
            holder.likeImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PostEvaluateLike(rowsBeans.get(position).getAdviceId(), !rowsBeans.get(position).isMyLikeState(), position);
                }
            });
            holder.reply.setVisibility(View.GONE);
        }

        @Override
        public int getItemCount() {
            return rowsBeans.size();
        }

        class RvViewHolder extends RecyclerView.ViewHolder {
            private ImageView head;
            private LinearLayout likeLL;
            private ImageView likeImg;
            private TextView likeNum;
            private TextView name;
            private TextView date;
            private RatingBar score;
            private TextView level;
            private TextView content;
            private CardView reply;
            private TextView replyTime;
            private TextView replyContent;

            public RvViewHolder(@NonNull View itemView) {
                super(itemView);
                head = itemView.findViewById(R.id.head);
                likeLL = itemView.findViewById(R.id.likeLL);
                likeImg = itemView.findViewById(R.id.likeImg);
                likeNum = itemView.findViewById(R.id.likeNum);
                name = itemView.findViewById(R.id.name);
                date = itemView.findViewById(R.id.date);
                score = itemView.findViewById(R.id.score);
                level = itemView.findViewById(R.id.level);
                content = itemView.findViewById(R.id.content);
                reply = itemView.findViewById(R.id.reply);
                replyTime = itemView.findViewById(R.id.replyTime);
                replyContent = itemView.findViewById(R.id.replyContent);
            }
        }
    }

}